# -*- coding: utf-8 -*-
"""
管理员管理模块 - 数据模型定义

本文件定义了测试DEMO中管理员管理相关的所有数据模型，包括：
1. AdminUser - 管理员用户模型，扩展基础用户信息，添加管理员特有属性
2. Role - 角色模型，定义系统中的各种角色
3. Permission - 权限模型，定义系统中的各种操作权限
4. RolePermission - 角色权限关联模型，实现角色与权限的多对多关系
5. UserRole - 用户角色关联模型，实现用户与角色的多对多关系
6. AuditLog - 审计日志模型，记录系统中的所有操作行为
7. SystemConfig - 系统配置模型，存储系统的各种配置参数

这些模型共同构成了完整的RBAC（基于角色的访问控制）权限管理体系，
确保系统的安全性和可管理性。

Author: zhaozeliang
Date: 2025-09-06
"""

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone
from users.models import User


class AdminUser(models.Model):
    """
    管理员用户模型
    """
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='admin_profile')
    admin_level = models.CharField(
        max_length=20,
        choices=[
            ('super', '超级管理员'),
            ('admin', '系统管理员'),
            ('operator', '运营管理员'),
            ('viewer', '只读管理员')
        ],
        default='viewer'
    )
    department = models.CharField(max_length=100, blank=True, null=True, verbose_name='部门')
    position = models.CharField(max_length=100, blank=True, null=True, verbose_name='职位')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    last_login_ip = models.GenericIPAddressField(blank=True, null=True, verbose_name='最后登录IP')
    last_login_time = models.DateTimeField(blank=True, null=True, verbose_name='最后登录时间')
    
    class Meta:
        db_table = 'admin_users'
        verbose_name = '管理员用户'
        verbose_name_plural = '管理员用户'
    
    def __str__(self):
        return f'{self.user.username} - {self.get_admin_level_display()}'


class Role(models.Model):
    """
    角色模型
    """
    name = models.CharField(max_length=50, unique=True, verbose_name='角色名称')
    code = models.CharField(max_length=50, unique=True, verbose_name='角色代码')
    description = models.TextField(blank=True, null=True, verbose_name='角色描述')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        db_table = 'roles'
        verbose_name = '角色'
        verbose_name_plural = '角色'
    
    def __str__(self):
        return self.name


class Permission(models.Model):
    """
    权限模型
    """
    name = models.CharField(max_length=100, verbose_name='权限名称')
    code = models.CharField(max_length=100, unique=True, verbose_name='权限代码')
    resource = models.CharField(max_length=100, verbose_name='资源')
    action = models.CharField(
        max_length=20,
        choices=[
            ('create', '创建'),
            ('read', '读取'),
            ('update', '更新'),
            ('delete', '删除'),
            ('execute', '执行')
        ],
        verbose_name='操作'
    )
    description = models.TextField(blank=True, null=True, verbose_name='权限描述')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'permissions'
        verbose_name = '权限'
        verbose_name_plural = '权限'
        unique_together = ['resource', 'action']
    
    def __str__(self):
        return f'{self.resource}:{self.action}'


class RolePermission(models.Model):
    """
    角色权限关联模型
    """
    role = models.ForeignKey(Role, on_delete=models.CASCADE, related_name='role_permissions')
    permission = models.ForeignKey(Permission, on_delete=models.CASCADE, related_name='permission_roles')
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'role_permissions'
        verbose_name = '角色权限'
        verbose_name_plural = '角色权限'
        unique_together = ['role', 'permission']
    
    def __str__(self):
        return f'{self.role.name} - {self.permission.code}'


class UserRole(models.Model):
    """
    用户角色关联模型
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_roles')
    role = models.ForeignKey(Role, on_delete=models.CASCADE, related_name='role_users')
    assigned_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='assigned_roles')
    assigned_at = models.DateTimeField(auto_now_add=True)
    expires_at = models.DateTimeField(blank=True, null=True, verbose_name='过期时间')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    
    class Meta:
        db_table = 'user_roles'
        verbose_name = '用户角色'
        verbose_name_plural = '用户角色'
        unique_together = ['user', 'role']
    
    def __str__(self):
        return f'{self.user.username} - {self.role.name}'
    
    def is_expired(self):
        if self.expires_at:
            return timezone.now() > self.expires_at
        return False


class AuditLog(models.Model):
    """
    审计日志模型
    """
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name='操作用户')
    action = models.CharField(max_length=100, verbose_name='操作动作')
    resource = models.CharField(max_length=100, verbose_name='操作资源')
    resource_id = models.CharField(max_length=100, blank=True, null=True, verbose_name='资源ID')
    ip_address = models.GenericIPAddressField(verbose_name='IP地址')
    user_agent = models.TextField(blank=True, null=True, verbose_name='用户代理')
    request_data = models.JSONField(blank=True, null=True, verbose_name='请求数据')
    response_data = models.JSONField(blank=True, null=True, verbose_name='响应数据')
    status = models.CharField(
        max_length=20,
        choices=[
            ('success', '成功'),
            ('failed', '失败'),
            ('error', '错误')
        ],
        default='success',
        verbose_name='状态'
    )
    error_message = models.TextField(blank=True, null=True, verbose_name='错误信息')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'audit_logs'
        verbose_name = '审计日志'
        verbose_name_plural = '审计日志'
        ordering = ['-created_at']
    
    def __str__(self):
        return f'{self.user.username if self.user else "Unknown"} - {self.action} - {self.resource}'


class SystemConfig(models.Model):
    """
    系统配置模型
    """
    key = models.CharField(max_length=100, unique=True, verbose_name='配置键')
    value = models.TextField(verbose_name='配置值')
    description = models.TextField(blank=True, null=True, verbose_name='配置描述')
    data_type = models.CharField(
        max_length=20,
        choices=[
            ('string', '字符串'),
            ('integer', '整数'),
            ('float', '浮点数'),
            ('boolean', '布尔值'),
            ('json', 'JSON')
        ],
        default='string',
        verbose_name='数据类型'
    )
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name='更新人')
    
    class Meta:
        db_table = 'system_configs'
        verbose_name = '系统配置'
        verbose_name_plural = '系统配置'
    
    def __str__(self):
        return f'{self.key}: {self.value}'
    
    def get_typed_value(self):
        """根据数据类型返回正确类型的值"""
        if self.data_type == 'integer':
            return int(self.value)
        elif self.data_type == 'float':
            return float(self.value)
        elif self.data_type == 'boolean':
            return self.value.lower() in ['true', '1', 'yes']
        elif self.data_type == 'json':
            import json
            return json.loads(self.value)
        return self.value
